/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        bool flag = false;
        ListNode* slow = head;
        ListNode* fast = head;

        //找到相交节点
        while (fast && fast->next)
        {
            slow = slow->next;
            fast = fast->next->next;

            if (slow == fast)
            {
                flag = true;
                break;
            }
        }
        if (!flag)
            return nullptr;

        ListNode* cur = head;
        while (cur != slow)
        {
            cur = cur->next;
            slow = slow->next;
        }
        
        return cur;
    }
};